package org.ala.tiktools.sharddb.db.provider.hikari;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.ala.tiktools.sharddb.db.config.ShardDataSourceConfigInfo;
import org.ala.tiktools.sharddb.db.provider.DiversionDataSourceProxy;
import org.ala.tiktools.sharddb.db.provider.IDatasourceProvider;

import javax.sql.DataSource;

/**
 * @author ala
 * @date 2025-03-25 11:55
 */
public class HikariCPDatasourceProvider implements IDatasourceProvider {
    @Override
    public String type() {
        return "hikari";
    }

    @Override
    public DataSource getDataSource(ShardDataSourceConfigInfo c) {
        return c.getDiversion() != null && c.getDiversion().isEnabled() ? getDiversionDataSource(c) : _getDataSource(c);
    }

    protected DataSource getDiversionDataSource(ShardDataSourceConfigInfo c) {
        return DiversionDataSourceProxy.build(c.getDiversion().getSize(), false, () -> _getDataSource(c));
    }
    protected DataSource _getDataSource(ShardDataSourceConfigInfo c) {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(c.getUrl());
        config.setUsername(c.getUsername());
        config.setPassword(c.getPassword());
        config.setMinimumIdle(c.getPool().getMinIdle());
        config.setMaximumPoolSize(c.getPool().getMaxActive());
        config.setConnectionTimeout(c.getPool().getMaxWait());
        config.setConnectionTimeout(c.getPool().getTimeBetweenEevictionRunsMillis());
        config.setConnectionTestQuery(c.getPool().getValidationQuery());
        return new HikariDataSource(config);
    }


    @Override
    public void closeDataSource(DataSource ds) {
        HikariDataSource d = (HikariDataSource) ds;
        d.close();
    }
}
